package com.heima.wemedia.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.heima.apis.article.IArticleClient;
import com.heima.common.aliyun.GreenImageScan;
import com.heima.common.aliyun.GreenTextScan;
import com.heima.common.tess4j.Tess4jClient;
import com.heima.file.service.FileStorageService;
import com.heima.model.article.dto.ArticleDto;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.wemedia.pojos.WmChannel;
import com.heima.model.wemedia.pojos.WmNews;
import com.heima.model.wemedia.pojos.WmSensitive;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.utils.common.SensitiveWordUtil;
import com.heima.wemedia.mapper.WmChannelMapper;
import com.heima.wemedia.mapper.WmNewsMapper;
import com.heima.wemedia.mapper.WmSensitiveMapper;
import com.heima.wemedia.mapper.WmUserMapper;
import com.heima.wemedia.service.WmNewsAutoScanService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.util.*;
import java.util.stream.Collectors;

@Service
@Slf4j
@Transactional
public class WmNewsAutoScanServiceImpl implements WmNewsAutoScanService {

    @Autowired
    private WmNewsMapper wmNewsMapper;

    @Autowired
    private GreenTextScan greenTextScan;

    @Autowired
    private GreenImageScan greenImageScan;

    @Autowired
    private FileStorageService fileStorageService;

    @Autowired
    private IArticleClient articleClient;

    @Autowired
    private WmUserMapper wmUserMapper;

    @Autowired
    private WmChannelMapper wmChannelMapper;

    @Autowired
    private WmSensitiveMapper wmSensitiveMapper;

    @Autowired
    private Tess4jClient tess4jClient;

    /**
     * 审核文章信息
     * id 文章id
     */
    @Override
    @Async
    public void autoScanWmNews(Integer id) {

//        try {
//            Thread.sleep(3000);
//        } catch (InterruptedException e) {
//            e.printStackTrace();
//        }
//        查询文章信息
        WmNews wmNews = wmNewsMapper.selectById(id);

        if (wmNews == null) {
            throw new RuntimeException("文章信息为空");
        }

//        判断当前是否要审核
        if (wmNews.getStatus().equals(WmNews.Status.SUBMIT.getCode())) {
            //            获取图片和文本信息
            Map<String, Object> map = getCommnetOrImages(wmNews);

//        审核文章
            Boolean flag = checkHasCommnet(map.get("content").toString(), wmNews);
            if (!flag) return;

//            审核图片
            Boolean aBoolean = checkHasImages((List<String>) map.get("images"), wmNews);
            if (!aBoolean) return;

            //            自定义敏感词汇
            stopSensitives(wmNews, wmNews.getContent());

            //4.审核成功，保存app端的相关的文章数据
            ResponseResult responseResult = saveAppArticle(wmNews);
//            成功是200
            if (!responseResult.getCode().equals(200)) {
                throw new RuntimeException("WmNewsAutoScanServiceImpl-文章审核，保存app端相关文章数据失败");
            }
            //回填article_id
            wmNews.setArticleId((Long) responseResult.getData());
//            设置已经审核通过
            updateWmNews(wmNews, (short) 9, "审核成功");
        }


    }

    //            自定义感感词汇
    private boolean stopSensitives(WmNews wmNews, String content) {

        boolean flag = true;

        List<WmSensitive> wmSensitives = wmSensitiveMapper.selectList(null);
//            提取字段词汇
        List<String> sensitives = wmSensitives.stream().map(WmSensitive::getSensitives).collect(Collectors.toList());
//            初始化铭感词
        SensitiveWordUtil.initMap(sensitives);

//            匹配铭感词汇
        Map<String, Integer> integerMap = SensitiveWordUtil.matchWords(content);
        if (integerMap.size() > 0) {
//                匹配到铭感词汇
            updateWmNews(wmNews, (short) 2, "当前文章中存在违规内容" + integerMap);
            flag = false;
        }
        return flag;

    }

    //    保存数据
    public ResponseResult saveAppArticle(WmNews wmNews) {

        ArticleDto articleDto = new ArticleDto();
        BeanUtils.copyProperties(wmNews, articleDto);
//        频道名称
        WmChannel wmChannel = wmChannelMapper.selectById(wmNews.getChannelId());

//        设置用户id
        articleDto.setAuthorId(wmNews.getUserId().longValue());

        articleDto.setChannelName(wmChannel.getName());
//        作者名称
        WmUser wmUser = wmUserMapper.selectById(wmNews.getUserId());
        articleDto.setAuthorName(wmUser.getName());
//        布局设置
        articleDto.setLayout(wmNews.getType());

//        证明是修改文章
        if (wmNews.getArticleId() != null) {
            articleDto.setId(wmNews.getArticleId());
        }
        articleDto.setCreatedTime(new Date());

        ResponseResult responseResult = articleClient.saveArticle(articleDto);

        return responseResult;
    }

    //    审核图片
    private Boolean checkHasImages(List<String> images, WmNews wmNews) {

        boolean flag = true;

        if (images == null || images.size() == 0) {
            return flag;
        }

//        去除重复图片
        images = images.stream().distinct().collect(Collectors.toList());

        List<byte[]> imageurls = new ArrayList<>();
//              先下载图片西欧你minio
        for (String image : images) {
            byte[] bytes = fileStorageService.downLoadFile(image);

            try {
//            审核图片中的文字内容
                //从byte[]转换为butteredImage
                ByteArrayInputStream inputStream = new ByteArrayInputStream(bytes);
                BufferedImage bufferedImage = ImageIO.read(inputStream);
//              转化为文字
                String result = tess4jClient.doOCR(bufferedImage);
                //审核是否包含自管理的敏感词
                Boolean isResult = checkHasCommnet(result, wmNews);

                if (!isResult) {
                    return isResult;
                }
                imageurls.add(bytes);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        try {
            Map map = greenImageScan.imageScan(imageurls);
            if (map != null) {
                //审核失败
                if (map.get("suggestion").equals("block")) {
                    flag = false;
                    updateWmNews(wmNews, (short) 2, "当前文章中存在违规内容");
                }

                //不确定信息  需要人工审核
                if (map.get("suggestion").equals("review")) {
                    flag = false;
                    updateWmNews(wmNews, (short) 3, "当前文章中存在不确定内容");
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return flag;
    }

    //        审核文章
    private Boolean checkHasCommnet(String content, WmNews wmNews) {

        boolean flag = true;

        if (StringUtils.isEmpty(content + "-" + wmNews.getTitle())) {
            return null;
        }
        try {
            Map map = greenTextScan.greeTextScan(content + "-" + wmNews.getTitle());
            if (map != null) {
                //审核失败
                if (map.get("suggestion").equals("block")) {
                    flag = false;
                    updateWmNews(wmNews, (short) 2, "当前文章中存在违规内容");
                }

                //不确定信息  需要人工审核
                if (map.get("suggestion").equals("review")) {
                    flag = false;
                    updateWmNews(wmNews, (short) 3, "当前文章中存在不确定内容");
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
        }

        return flag;
    }

    //            获取图片和文本信息
    private Map<String, Object> getCommnetOrImages(WmNews wmNews) {

        //            用户手机文本内容
        StringBuilder stringBuilder = new StringBuilder();

        List<String> images = new ArrayList<>();

        if (StringUtils.isNotEmpty(wmNews.getContent())) {
            List<Map> maps = JSONArray.parseArray(wmNews.getContent(), Map.class);
            for (Map map : maps) {
                if (map.get("type").equals("text")) {
                    stringBuilder.append(map.get("value"));
                }
                if (map.get("type").equals("image")) {
                    String url = map.get("value").toString();
                    images.add(url);
                }
            }

            //        获取封面图片
            if (StringUtils.isNotEmpty(wmNews.getImages())) {
                String[] split = wmNews.getImages().split(",");
                images.addAll(Arrays.asList(split));
            }

        }
        Map<String, Object> result = new HashMap<>();
        result.put("content", stringBuilder);
        result.put("images", images);
        return result;
    }

//    修改文章内容

    public void updateWmNews(WmNews wmNews, short type, String reason) {
        wmNews.setReason(reason);
        wmNews.setStatus(type);
        wmNewsMapper.updateById(wmNews);
    }


}



